package com.google.code.sharecontent.action;

import java.sql.SQLException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

import com.google.code.sharecontent.model.Group;
import com.google.code.sharecontent.model.User;

@Name("authenticator")
public class LoginAction {


	@Logger
	protected Log log;
	
    @In
    private FacesMessages facesMessages;

	@In 
	@Out
	Identity identity;
	
	@In("daoAction") DaoAction daoAction;
	
	@In(required=false)
	@Out(required=false,scope=ScopeType.SESSION,value="user")
	User user;

    public boolean authenticate()
    {
        System.out.println("###### Authenticate called ##########");
        User user = null;
		try {
			user = daoAction.getUserDao().findByUsernamePassword(identity.getUsername(), identity.getPassword());
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
        if (user != null) {
        	this.user = user;
        	for (Group group : user.getGroups()) {
        		identity.addRole(group.getCode());
        	}
        	return true;
        }
//        loggedIn=false;
//        login() ;
        return false;
    }

}
